#coding=utf-8
import sys, xml.dom.minidom,os
import urllib,urllib2,re,json
import threading, time
class Passcode:
	def __init__(self,APIkey = None):
		self.address = 'http://decodeingress.me/feed/'
		self.filename = 'passcode.txt'
		self.APIkey = APIkey
	def get_old_passcode(self):
		file =open(self.filename,'r')
		oldstr = file.read()
		file.close()
		old = oldstr.split('\n')
		return old
	def get_passcode_from_feed(self):
		lastest = []
		document = xml.dom.minidom.parse(urllib.urlopen(self.address))
		for item in document.getElementsByTagName('item'):
			title = item.getElementsByTagName('title')[0].firstChild.data
			if 'passcode' in title.lower():
				for each in title.split(' '):
					if 'passcode' not in each.lower():
						lastest.append(each)	
		return lastest
	def get_passcode_from_gplus(self):
		gplusaddr = 'https://www.googleapis.com/plus/v1/activities?query=passcode&maxResults=20&fields=items(annotation%2Cobject(attachments%2Fcontent%2Ccontent%2CoriginalContent)%2Ctitle)%2Ctitle&key='+ self.APIkey
		page=urllib.urlopen(gplusaddr)
		data=page.read()
		allpasscode = re.findall('\d[A-Za-z]{2}\d[A-Za-z]+\d[A-Za-z]\d[A-Za-z]', data)
		lastest = []
		for each in allpasscode:
			if each not in lastest:
				lastest.append(each)
		return lastest
	def checknew(self):
		needupdate = []
		old = Passcode.get_old_passcode(self)
		lastest_feed = Passcode.get_passcode_from_feed(self)
		lastest_gplus = Passcode.get_passcode_from_gplus(self)
		for each in lastest_gplus + lastest_feed:
			if each not in old:
				if each not in needupdate:
					print "[i]:found new passcode:",each
					needupdate.append(each)
		if len(needupdate)>0:
			Passcode.store(self,needupdate+old)
		return needupdate
	
	def checkexists(self):
		if not os.path.exists(self.filename):
			print ("[w]:creating passcode.txt")
			Passcode.store(self,Passcode.get_passcode_from_feed(self))
			print ("[i]:creating successful")
		else:
			print ("[i]:check passcode.txt ....PASSED")

	def store(self,lastest):
		file = open(self.filename,'w')
		for each in lastest:
			file.write(each+'\n')
		file.close()
class Ingress:
	def __init__(self, email = None, password = None):
		self.email=email
		self.password=password
	def login(self):
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
		urllib2.install_opener(self.opener)
		# Define URLs
		self.ingress_url='http://www.ingress.com/intel'
		self.loing_page_url = 'https://accounts.google.com/ServiceLogin?service=grandcentral'
		self.authenticate_url = 'https://accounts.google.com/ServiceLoginAuth'
		self.passcode_url = 'http://www.ingress.com/rpc/dashboard.redeemReward'

		#Load longin url
		print '[i]:Search url...'
		ingress_page_contents = self.opener.open(self.ingress_url).read()
		loing_page_url=re.findall('<a href="(.*?)" class="button_link"',ingress_page_contents,re.I)

		ltmpl_shdf=re.findall('ltmpl=(.*?)&shdf=(.*)',loing_page_url[0],re.I)
		login_page_contents = self.opener.open(loing_page_url[0]).read()

		print '[i]:Search GALX...'
		# Find GALX value
		galx_match_obj = re.search(r'name="GALX"\s*value="([^"]+)"', login_page_contents, re.IGNORECASE)
		galx_value = galx_match_obj.group(1) if galx_match_obj.group(1) is not None else ''

		login_params = urllib.urlencode({
					'Email' : self.email,
					'Passwd' : self.password,
					'continue' : 'https://appengine.google.com/_ah/conflogin?continue=http://www.ingress.com/intel',
					'GALX' : galx_value,
					'signIn' : 'Sign in',
					'service' : 'ah',
					'shdf' : ltmpl_shdf[0][1],
					'ltmpl' : ltmpl_shdf[0][0]

				})
		#Lgoin Ingress
		print '[i]:Login '+self.email+' ...'
		self.opener.open(self.authenticate_url, login_params)
		ingress_page_contents = self.opener.open(self.ingress_url).read()

		toekn = re.search("name='csrfmiddlewaretoken'.*?value='(.*?)'", ingress_page_contents)
		if not toekn:
			self.logged_in = False
			print '[e]:Login failed'
		else:
			self.logged_in = True
			self.toekn = toekn.group(1)
			print '[i]:Login Success,toekn:'+self.toekn

	def send_passcode(self,passcode):
		print "[i]:sending passcode:",passcode
		data_json = json.dumps({"passcode":passcode,"method":"dashboard.redeemReward"}) 
		req = urllib2.Request(self.passcode_url, data=data_json)
		req.add_header('Referer','http://www.ingress.com/intel')
		req.add_header('X-CSRFToken',self.toekn)
		req.add_header('Connection','keep-alive')
		req.add_header('X-Requested-With','XMLHttpRequest')
		response=urllib2.urlopen(req)
		result = response.read()
		try:
			error = json.loads(result)["error"]
			print error
		except:
			gameBasket = json.loads(result)["gameBasket"]
			print gameBasket
		
	
		

def t_start(Ingress,Passcode):
	t = threading.Timer(120,t_refresh,(Ingress,Passcode))
	t.start()

def t_refresh(Ingress,Passcode):
	splitPost(Ingress,Passcode)
	t_start(Ingress,Passcode)

def splitPost(Ingress,Passcode):
	passcodes = Passcode.checknew()
	current= time.strftime('%Y%m%d %H:%M:%S',time.localtime(time.time()))
	if len(passcodes)>0:
		print "[i]:"+current+" submiting passcodes..."
		for passcode in passcodes:
			Ingress.send_passcode(passcode)
	else:
		print "[i]:"+current+" no new passcode ! "
		
#main
if __name__ == "__main__":
	print u"passcode 自动提交脚本 v0.2"
	print u"第一次使用请填写Email和密码，然后去https://code.google.com/apis/console/注册g+api"
	print u"确认以上信息后请回车 Enter"
	command = raw_input()
	igrss = Passcode('你的APIkey')
	igrss.checkexists()
	ingress=Ingress('你的邮箱@gmail.com','你的密码')
	ingress.login()
	splitPost(ingress,igrss)
	t_start(ingress,igrss)
	while True:
		time.sleep(1)